package com.ym.b2b.order.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.commons.service.BaseService;
import com.ym.b2b.order.dao.EmShoppingCartDao;
import com.ym.b2b.order.dao.impl.EmShoppingCartDaoImpl;
import com.ym.b2b.order.service.EmShoppingCartService;
import com.ym.b2b.order.sqlbean.EmSShoppingCart;
import com.ym.b2b.product.dao.EmKStorageDao;
import com.ym.b2b.product.dao.ProductDao;
import com.ym.b2b.product.sqlbean.EmBProduct;
import com.ym.b2b.product.sqlbean.EmKStorage;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;

import java.util.Date;

@Service
public class EmShoppingCartServiceImpl extends BaseService implements EmShoppingCartService {

    private Logger            logger = Logger.getLogger(getClass());
    @Autowired
    private EmShoppingCartDao emShoppingCartDao;

    @Autowired
    private ProductDao        productDao;

    @Autowired
    private EmKStorageDao     emKStorageDao;

    @Override
    public Result addShoppingCart(EmSShoppingCart emSShoppingCart) {
        if (null == emSShoppingCart.getAmount()) {
            emSShoppingCart.setAmount(1.0);
        }
        // 查库存
        Result result = checkProductStock(emSShoppingCart);
        if (result.getCode().equals("100")) {
            return result;
        }
        try {
        	// 判断是否已经在购物车内
            emSShoppingCart.setBuyerCode(emSShoppingCart.getTokenUser().getBuyerCode());
            Integer isexit = emShoppingCartDao.isExitShoppintCart(emSShoppingCart);
            if (isexit > 0) {
                result.setCodeResult(Result.CODE_100, "SORRY.商品已存在  需要修改数量可进入购物车修改!");
                return result;
            }
            // 判断购物车内产品种类是否查过99个
            EmSShoppingCart emSShoppingCart2 = new EmSShoppingCart();
            emSShoppingCart2.setBuyerCode(emSShoppingCart.getTokenUser().getBuyerCode());
            Integer SumProduct = emShoppingCartDao.isExitShoppintCart(emSShoppingCart2);
            if (SumProduct > 99) {
                result.setCodeResult(Result.CODE_100, "SORRY.单次购买的商品数量限制在‘100’个!如有疑问可咨询网络部.");
                return result;
            }

            // 判断产品是否限制销售,是否下架,是否审核通过,是否有最小购买限制
            EmBProduct svo = new EmBProduct();
            svo.setProductCode(emSShoppingCart.getProductCode());
            svo.setBuyerCode(emSShoppingCart.getTokenUser().getBuyerCode());
            svo.setAmount(emSShoppingCart.getAmount().doubleValue());
            EmBProduct emBProduct = productDao.showProductDetailConcise(svo);

            // 判断限制销售
            if (emBProduct == null) {
                result.setCodeResult(Result.CODE_100, "SORRY.商品不存在 或者此商品限制销售 具体咨询网络部!");
                return result;
            }
            // 查询是否 有最小购买限制
            if (emBProduct.getMinBuy().doubleValue() > 0) {
                if (emSShoppingCart.getAmount() % emBProduct.getMinBuy() > 0) {
                    result.setCodeResult(Result.CODE_100,
                                         "此商品有最小数量限制为：" + emBProduct.getMinBuy() + "" + emBProduct.getPackingUnit()
                                                 + ",请输入最小购买 的倍数!谢谢`~`");
                    return result;
                }
            }
            
            if(emBProduct.getIsSale() == 0){
            	result.setCodeResult(Result.CODE_100, "SORRY.该商品已经下架,无法购买!");
                return result;
            }
            if(emBProduct.getApproveStatus() == 0){
            	result.setCodeResult(Result.CODE_100, "SORRY.该商品未通过审核,无法购买!");
                return result;
            }
            emSShoppingCart.setLargePackageNum(emBProduct.getLargePackageNum());
            emSShoppingCart.setMiddlePackageNum(emBProduct.getMiddlePackageNum());

            emShoppingCartDao.addShoppingCart(emSShoppingCart);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, "添加到购物车失败!");
        }
        result.setResult(" 加入购物车 成功!");
        return result;
    }

    @Override
    public Result updateShoppingCart(EmSShoppingCart emSShoppingCart) throws BaseException {
        Result result = checkProductStock(emSShoppingCart);
        if (result.getCode().equals("100")) {
            return result;
        }
        try {

            EmBProduct svo = new EmBProduct();
            svo.setProductCode(emSShoppingCart.getProductCode());
            svo.setBuyerCode(emSShoppingCart.getTokenUser().getBuyerCode());
            svo.setAmount(emSShoppingCart.getAmount().doubleValue());
            EmBProduct emBProduct = productDao.showProductDetailConcise(svo);

            // 判断限制销售
            if (emBProduct == null) {
                result.setCodeResult(Result.CODE_100, " 商品不存在 或者此商品限制销售 具体咨询网络部!");
                return result;
            }
            // 查询是否 有最小购买限制
            if (emBProduct.getMinBuy().doubleValue() > 0) {
                logger.info("running result:" + emSShoppingCart.getAmount() / emBProduct.getMinBuy());
                if (emSShoppingCart.getAmount() % emBProduct.getMinBuy() > 0) {
                    result.setCodeResult(Result.CODE_100,
                                         "此商品有最小数量限制为：" + emBProduct.getMinBuy() + "" + emBProduct.getPackingUnit()
                                                 + ",请输入最小购买 的倍数!谢谢`~`");
                    return result;
                }
            }

            emSShoppingCart.setLargePackageNum(emBProduct.getLargePackageNum());
            emSShoppingCart.setMiddlePackageNum(emBProduct.getMiddlePackageNum());
            emShoppingCartDao.updateShoppingCart(emSShoppingCart);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, " 修改购物车 记录异常 请通知管理员!");
        }
        return result;
    }

    private Result checkProductStock(EmSShoppingCart emSShoppingCart) {
        Result result = new Result();
        // 判断库存是否足够
        EmKStorage emKStorage = new EmKStorage();
        emKStorage.setProductCode(emSShoppingCart.getProductCode());
        emKStorage.setExpirydate(new Date());
        try {
            emKStorage = emKStorageDao.showEmKStorageForAmount(emKStorage);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(e.getMessage());
        }
        if (emKStorage == null) {
            result.setCodeResult(Result.CODE_100, "库存不足.");
            return result;
        }
        if (emSShoppingCart.getAmount().doubleValue() > emKStorage.getAmount().doubleValue()) {
            result.setCodeResult(Result.CODE_100, "库存不足.剩余库存为：" + emKStorage.getAmount());
            return result;
        }
        return result;
    }

    @Override
    public Result searchPageShoppingCart(EmSShoppingCart emSShoppingCart, Page<EmSShoppingCart> page)
                                                                                                     throws BaseException {
        Result result = new Result();
        try {
            page.setPageSize(1000);
            doShoppintCartToken(emSShoppingCart);
            if (emShoppingCartDao == null) {
                emShoppingCartDao = new EmShoppingCartDaoImpl();
            }

            result.setResultPage(emShoppingCartDao.searchPageShoppingCart(emSShoppingCart, page));
            result.putData("sumMoney", emShoppingCartDao.countShoppintCartTotalMoeny(emSShoppingCart));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("查询购物车 失败");
        }
        return result;
    }

    private void doShoppintCartToken(EmSShoppingCart emSShoppingCart) {
        emSShoppingCart.setBuyerCode(emSShoppingCart.getTokenUser().getBuyerCode());
        emSShoppingCart.setIsBranch(emSShoppingCart.getTokenUser().getIsBranch() == null ? 0 : emSShoppingCart.getTokenUser().getIsBranch());
        emSShoppingCart.setPayType(emSShoppingCart.getTokenUser().getPayType());
    }

    @Override
    public Result deleteShoppingCart(EmSShoppingCart emSShoppingCart) throws BaseException {
        Result result = new Result();
        try {
            doShoppintCartToken(emSShoppingCart);
            emShoppingCartDao.deleteShoppingCart(emSShoppingCart);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }
}
